import React, { Component } from 'react'
// 类组件计算组件(相同的运算则会进行缓存)，它需要安装 npm i -S memoize-one
import memoizeOne from 'memoize-one'

class App extends Component {
  state = {
    n1: 1,
    n2: 2
  }

  // 调用方法没有缓存，相同的计算如果有缓存则性能会更好
  sum = (n1, n2) => {
    console.log('sum')
    return n1 + n2
  }

  // 计算属性，相邻的两个相同的运算则会缓存
  total = memoizeOne((n1, n2) => {
    console.log('memoizeOne')
    return n1 + n2
  })

  render() {
    let { n1, n2 } = this.state
    return (
      <div>
        {/* 不推荐，不在结构元素代码中写过多的逻辑 */}
        <h3>{n1 + n2}</h3>
        <h3>{this.sum(n1, n2)}</h3>
        <h3>{this.sum(n1, n2)}</h3>
        {/* 相邻的两个相同的运算则会缓存 */}
        <h3>{this.total(n1, n2)}</h3>
        <h3>{this.total(n1, n2)}</h3>
        <h3>{this.total(n1, n2)}</h3>
        <h3>{this.total(n1, n2)}</h3>
        <h3>{this.total(n1, n2)}</h3>
      </div>
    )
  }
}

export default App
